import { Injectable, NgModule } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, PreloadAllModules, Router, RouterModule, RouterStateSnapshot, Routes } from '@angular/router';
import { Observable } from 'rxjs';
import { MineService } from './service/mine.service';

@Injectable({
  providedIn: 'root'
})
export class LoginStatusGuard implements CanActivate {

  constructor(private router: Router, private mineService: MineService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
    return this.mineService.checkUserLogin().then(value => {
      console.log('是否登录：' + value, '请求路径：' + state.url)
      if (value && state.url == '/login') {
        this.router.navigate(['/tabs/chats'])
        return false
      }
      if (!value && state.url != '/login') {
        this.router.navigate(['/login'])
        return false
      }
      return true
    })
  }
}

const routes: Routes = [
  {
    path: '',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'chat',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./chats/chat/chat.module').then(m => m.ChatPageModule)
  },
  {
    path: 'person-info',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./me/person-info/person-info.module').then(m => m.PersonInfoPageModule)
  },
  {
    path: 'settings',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./me/settings/settings.module').then(m => m.SettingsPageModule)
  },
  {
    path: 'login',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./login/login.module').then(m => m.LoginPageModule)
  },
  {
    path: 'contacts',
    canActivate: [LoginStatusGuard],
    loadChildren: () => import('./address-book/contacts/contacts.module').then(m => m.ContactsPageModule)
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
